package com.isdepci.framework.task;

import com.isdepci.project.carbon.domain.CcerDataList;
import com.isdepci.project.carbon.domain.param.CcerData;
import com.isdepci.project.carbon.mapper.CcerDataListMapper;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component("ccerDataTask")
public class CcerDataTask {

    @Autowired
    private CcerDataListMapper ccerDataListMapper;

    private static final String LIST_URL = "https://ccer.cets.org.cn/api/projectmanage/open/getOpeningApply";
    private static final String DETAIL_URL = "https://ccer.cets.org.cn/api/projectmanage/open/getOpeningApplyDetail";



    public void fetchAndSaveCcerData() {
        // 1. 获取项目列表数据
        List<CcerData> dataList = fetchProjectList();
        //1.5先删除表中数据
        ccerDataListMapper.deleteALLCcerDataList();
        // 2. 获取并处理每个项目的详情
        for (CcerData item : dataList) {
            CcerDataList detail = fetchProjectDetail(item);
            if (detail != null) {
                // 3. 保存到数据库
                ccerDataListMapper.insertCcerDataList(detail);
            }
        }
    }

    private List<CcerData> fetchProjectList() {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("dataType", "4");
            params.put("pageNumber", 1);
            params.put("pageSize", 12);
            String responseBody = postJsonWithUtf8(LIST_URL, params);
            JSONObject json = JSON.parseObject(responseBody);
            if ("1".equals(json.getString("flag"))) {
                JSONArray dataInfo = json.getJSONArray("dataInfo");
                return dataInfo.toJavaList(CcerData.class);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Collections.emptyList();
    }

    private CcerDataList fetchProjectDetail(CcerData item) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("applyId", item.getApplyId());
            params.put("certificationId", item.getCertificationId());
            params.put("dataType", "4");
            params.put("ccerId", null);
            params.put("projectInfoId", null);
            params.put("applyStatus", null);
            String responseBody = postJsonWithUtf8(DETAIL_URL, params);
            JSONObject json = JSON.parseObject(responseBody);
            if ("1".equals(json.getString("flag"))) {
                JSONObject detailData = json.getJSONObject("dataInfo");
                return convertToEntity(detailData);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }



    private CcerDataList convertToEntity(JSONObject detail) {
        CcerDataList entity = new CcerDataList();
        entity.setProjectCode(detail.getString("projectCode")); // 项目编号
        entity.setProjectName(detail.getString("projectName")); // 项目名称
        entity.setProvince(detail.getString("provinceName"));   // 所属省份
        entity.setProjectLocation(detail.getString("projectLocation")); // 地理位置
        entity.setMethodology(detail.getString("projectTypeName")); // 方法学
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        try {
            entity.setStartTime(sdf.parse(detail.getString("registrationTime"))); // 计入期开始时间
            entity.setLastTime(sdf.parse(detail.getString("endReckonDate")));    // 计入期结束时间
        } catch (ParseException | NullPointerException e) {
            e.printStackTrace();
        }
        entity.setYearAvgEmission(parseBigDecimal(detail.get("expectYearNum"))); // 年均减排量
        entity.setTotalEmission(parseBigDecimal(detail.get("expectMaxNum")));     // 总减排量
        entity.setRegisterEmission(parseBigDecimal(detail.get("certifiedNum")));     // 申请登记减排量
        return entity;
    }

    private BigDecimal parseBigDecimal(Object value) {
        if (value == null) return null;
        try {
            return new BigDecimal(value.toString());
        } catch (NumberFormatException e) {
            return null;
        }
    }


    private String postJsonWithUtf8(String url, Map<String, Object> params) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);
            // 设置UTF-8请求头
            httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");
            httpPost.setHeader("Accept", "application/json");
            String jsonBody = JSON.toJSONString(params);
            httpPost.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8));
            // 执行请求并强制使用UTF-8解码响应
            return EntityUtils.toString(httpClient.execute(httpPost).getEntity(), StandardCharsets.UTF_8);
        }
    }


}
